package cn.nju.zyy.model.person;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

public class PersonDAOImpl implements PersonDAO {

	private SessionFactory sessionFactory;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public long savePerson(Person person) {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		long personId = -1;
		
		try {
			transaction = session.beginTransaction();
			personId = (Long) session.save(person);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return personId;
	}

	@Override
	public List<Person> listPerson() {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		List<Person> persons = null;
		
		try {
			transaction = session.beginTransaction();
			persons = session.createQuery("from Person").list();
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return persons;
	}

	@Override
	public Person getPerson(long id) {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		Person person = null;
		
		try {
			transaction = session.beginTransaction();
			person = (Person) session.get(Person.class, id);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return person;
	}

	@Override
	public void update(Person person) {
	}

	@Override
	public void delete(long id) {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		
		try {
			transaction = session.beginTransaction();
			Person person = (Person) session.get(Person.class, id);
			session.delete(person);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
